import sys
import re
from author_classifier1 import AccuracyCalculator

f = open(sys.argv[1], 'r')
tuple_output = []
classifier_dict = {}
classifier = ''
for line in f:
  m = re.match('^Classifier: (.*)$', line)
  if m:
    classifier = m.groups()[0]
    continue

  m = re.match('^Prediction: (.*), prob = (.*)$', line)
  if m:
    c_predicted = m.groups()[0]
    prob = float(m.groups()[1])
    classifier_dict[classifier] = (c_predicted, prob)
    continue 

  m = re.match('^(.*), (.*)$', line)
  if m:
    tuple_output.append((dict(classifier_dict), m.groups()[0]))
    classifier_dict.clear()

skip_list = [
  'readability_classifier',
  'stopwords_classifier',
  'tfiaf_classifier',
  #'ngram_classifier',
  'pos_classifier',
  #'charngram_classifier',
  ]

accuracy_calculator = AccuracyCalculator()

classifier_weight_dict = {
  'readability_classifier': 0.5,
  'stopwords_classifier': 1.0,
  'tfiaf_classifier': 0.5,
  'ngram_classifier': 1.0,
  'pos_classifier': 1.0,
  'charngram_classifier': 1.0,
}
#classifier_weight_dict = {
#  'readability_classifier': 0.364,
#  'stopwords_classifier': 0.985,
#  'tfiaf_classifier': 0.946,
#  'ngram_classifier': 0.999,
#  'pos_classifier': 0.980,
#}

def classify(classifiers):
  label_cnt = {}
  label_prob = {}
  max_label = ''  
  max_prob = 0.0
  max_cnt = 0
  for name in classifiers:
    classifier = classifiers[name]
    #print 'Classifier: %s' % name
    label = classifier[0]
    prob = classifier[1]
    #print 'Prediction: %s, prob = %0.3f' % (label, prob)
    if label not in label_cnt:
      label_cnt[label] = 0 

    if label not in label_prob:
      label_prob[label] = 1

    label_prob[label] = label_prob[label] * prob
    label_cnt[label] = label_cnt[label] + classifier_weight_dict[name]

    if label_cnt[label] == max_cnt:
      if label_prob[label] > max_prob:
        max_prob = label_prob[label]
        max_label = label

    if label_cnt[label] > max_cnt:
      max_cnt = label_cnt[label]
      max_label = label
      max_prob = label_prob[label]

  return max_label

for t in tuple_output:
  classifiers = t[0]
  for classifier in skip_list:
    classifiers.pop(classifier)
  label = classify(classifiers)
  accuracy_calculator.add_tuple(t[1], label)

accuracy_calculator.print_accuracy()
